import { Login,LoginByGid } from '@/api/data'
import { setToken, getToken,setAccess,getAccess ,getUserInfo,setUserInfo} from '@/libs/util'
export default {
  state: {
    userinfo:getUserInfo(),
    token: getToken(),
    access: getAccess(),
  },
  mutations:{
    setAccess(state, vaccess) {     
      state.access = vaccess;
      setAccess(vaccess)
    },
    setUserInfo(state, userinfo) {
      state.userinfo = userinfo;
      setUserInfo(userinfo);
    },
    setToken (state, token) { 
      state.token = token
      setToken(token)
    },  
  },
  actions: {  
    // 登录
    handleLogin({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        Login({
          account: userName,
          pwd: password
        }).then(res => {
          const data = res.data
          if (data.Type == 1) { 
            commit('setToken', data.Data.Token)
            commit('setAccess',data.Data.AuthRule);
            commit('setUserInfo',data.Data);
            resolve(data)            
          } else {
            resolve(data)    
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    handleLoginById ({ commit }, { id }) { 
      return new Promise((resolve, reject) => {
        LoginByGid(id).then(res => {         
          const data = res.data 
          if (data.Type == 1) {
            commit('setToken', data.Data.Token)
            commit('setAccess',data.Data.AuthRule);
            commit('setUserInfo',data.Data);
            resolve(data)            
          } else {
            resolve(data)            
          }         
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut() {
      return new Promise((resolve, reject) => {
        setToken('')
        setAccess('');
        resolve();
      })


    }

  }
}
